<?php

/**
 * Class for forming an RSS feed.
 * Extends ViewHtmlElement: same rules apply for XML.
 *
 * @author Ian Clarence ian.clarence@gmail.com
 */ 
abstract class ViewRssFeed extends ViewHtmlElement {

    /**
     * The constructor.
     *
     * @param array $fields
     */
    public function __construct(array $fields = array()) {   
        $fields['tag'] = 'rss';     
        parent::__construct($fields);
        $this->setAttribute('version', '2.0');
        $this->addInnerHtml($this->getChannel());
    }

    /**
     * getting the channel for the feed.
     *
     * @return ViewHtmlElement
     */
    protected function getChannel() {
        $channel = ViewHtmlElement::elementInit('channel', NULL);
        $channel->addTitle($this->fields['page']['title_text']);
        $channel->addDescription($this->fields['page']['description']);
        $channel->addLink($this->fields['page']['full_url']);
        $channel->addLastBuildDate(date('r'));
        $channel->addPubDate(date('r'));
        $channel->addTtl($this->fields['page']['id']);
        
        /**
         * Feed items. 
         */
        foreach ($this->fields['panels'] as $panel) {
            if ($panel['panel_type'] == 6) {
                foreach ($panel['articles'] as $article) {
                    if (is_array($article) && $article['heading_text']) {
                        $item = ViewHtmlElement::elementInit('item', NULL);
                        $item->addTitle($article['heading_text']);
                        $item->addDescription($article['short_content_text']);
                        $item->addLink(ViewUtils::addUrlComponent($this->fields['page']['full_url'], ARTICLE_PREFIX . $article['id']));
                        $item->addGuid($article['name']);
                        $item->addPubDate(date('r'));
                        $channel->addInnerHtml($item);
                    }
                }
            }
        }
        $channel->addItem();
        return $channel;
    }

    /**
     * Viewing the entire element.
     *
     * @return string
     */
    public function view() {

        /**
         * XML declaration.
         */
        $output = '<?xml version="1.0" encoding="' . CHARSET . '" ?>' . "\n";

        /**
         * Normal viewing.
         */
        $output .= parent::view();

        /**
         * Final text string.
         */
        return $output;
    }
    
}